<!--  添加今日爆款活动 operate:market:today:add-->
<template>
  <div class="content">
    <el-form :model="data" :rules="rules" ref="formData" size="medium" label-width="100px">
      <el-row class="row-info">
        <div class="title">基本设置</div>
        <el-form-item label="活动名称：" prop="title">
          <el-input style="width:320px;" v-model="data.title" placeholder="请输入活动名称(20字内)" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="开始时间：" prop="startTime">
          <TimePicker v-model="data.startTime" :needPickerOptions="false" type="datetime" placeholder="请选择活动开始时间"></TimePicker>
        </el-form-item>
        <el-form-item label="结束时间：" prop="endTime">
          <TimePicker v-model="data.endTime" :needPickerOptions="false" type="datetime" :defaultTime="'23:59:59'"
                      placeholder="请选择活动结束时间"></TimePicker>
        </el-form-item>
        <el-form-item label="活动状态：" prop="status">
          <el-radio-group v-model="data.status">
            <el-radio :label="v.value" v-for="(v, index) in marketStatus" :key="index">{{v.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>

      <el-row class="row-info">
        <div class="title">规则设置</div>
        <el-form-item label="活动对象：" prop="">
          全部用户
        </el-form-item>
        <el-form-item label="限购设置：" prop="buyerLimit">
          <el-radio-group v-model="buyerLimitType">
            <el-radio :label="'1'">不限购</el-radio>
            <el-radio :label="'2'">
              限购
              <el-input :disabled="buyerLimitType !== '2'" style="width: 130px; margin-left: 20px;" v-model="buyerLimitNum"
                        placeholder="请输入购买次数"></el-input>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品价格：" prop="payWay">
          <el-radio-group v-model="data.payWay" @change="hanldeActivityChange">
            <el-radio :label="v.value" v-for="(v, index) in activityPayWay" :key="index">{{v.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品排序：" prop="">
          <el-radio-group v-model="data.sort" @change="hanldeActivitySortChange">
            <el-radio :label="v.value" v-for="(v, index) in activitySort" :key="index">{{v.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="选择商品：" prop="productData">
          <div>
            <span class="click-ele" style="font-size:12px;margin: 0;" @click="addDialogShow = true">添加商品</span>
            <SelectedPro></SelectedPro>
          </div>
        </el-form-item>
      </el-row>

      <el-row class="row-info" style="padding:0 30px 50px 100px;">
        <el-button size="medium" @click="handleCancle('formData')">取 消</el-button>
        <el-button :loading="btnLoading" size="medium" type="primary" @click="handleSub('formData')">添 加</el-button>
      </el-row>

    </el-form>

    <SelectProduct v-if="addDialogShow" :modalShow.sync="addDialogShow"></SelectProduct>
  </div>
</template>

<script>
import { CreateMarket } from '@/api/onlineMan'
import { ExportList } from '@/utils'
import { activityFormRules } from '@/utils/rules'
import TimePicker from '@/components/DatePicker/TimePicker'
import SelectProduct from '@/components/SelectProduct/selectPro'
import SelectedPro from '@/components/SelectProduct/selectedPro'
export default {
  name: 'newAdd',
  components: { TimePicker, SelectProduct, SelectedPro },
  data () {
    return {
      marketStatus: ExportList('marketStatus'),
      activityPayWay: ExportList('activityPayWay'),
      activitySort: ExportList('activitySort'),
      buyerLimitType: '1',
      buyerLimitNum: '',
      data: {
        type: '2',
        buyerLimit: '',
        title: '',
        startTime: '',
        endTime: '',
        description: '',
        status: '0',
        payWay: '0',
        sort: 'def',
        productData: [],
        products: []
      },
      rules: activityFormRules,
      selectProducts: [],
      addDialogShow: false,
      btnLoading: false
    }
  },
  props: {},
  watch: {
    'selectedProductList': function (val) {
      this.handleSelectProduct(val)
    },
    'buyerLimitType': function (value) {
      if (value === '1') {
        this.buyerLimitNum = ''
      }
    }
  },
  computed: {
    selectedProductList () {
      return this.$store.state.selectProduct.selectedProductList
    }
  },
  mounted () { },
  methods: {
    hanldeActivityChange (val) {
      this.$store.dispatch('setActivityPayWay', val)
    },
    hanldeActivitySortChange (val) {
      this.$store.dispatch('setActivitySort', val)
    },
    handleCancle () {
      const backTips = this.$router.currentRoute.meta.backTips
      if (backTips) {
        this.$confirm(backTips, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.go(-1)
        }).catch(() => { })
      } else {
        this.$router.go(-1)
      }
    },
    handleSub (formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) return false
        let params = JSON.parse(JSON.stringify(this.data))
        params.startTime = new Date(params.startTime)
        params.endTime = new Date(params.endTime)
        if (new Date(params.startTime).getTime() >= new Date(params.endTime).getTime()) {
          this.$message.warning('开始时间不得在结束时间之后！')
          return
        }
        if (this.checkIsSpec()) {
          this.$message.warning('添加的商品中存在未选择规格的商品！')
          return
        }
        delete params.productData
        params.buyerLimit = this.buyerLimitType === '1' ? '0' : this.buyerLimitNum

        this.btnLoading = true
        CreateMarket(params).then(res => {
          this.btnLoading = false
          this.$message.success(res.message || '操作成功')
          this.$router.push({ name: 'operate:market:today' })
        }).catch(e => {
          this.btnLoading = false
        })
      })
    },
    // 检查添加的商品中 多规格数据是否 还有没有未选择规格的商品
    checkIsSpec () {
      let count = 0 // 计数
      // 商品为多规格 不存在或者长度为0 加一下 内部没有选择规格(selected===true)一个也没
      this.selectedProductList.forEach(e => {
        if (e.productStyle === 2) {
          if (!e.stocks || e.stocks.length <= 0) {
            count++
          } else {
            let count2 = 0
            e.stocks.forEach(item => {
              if (item.selected) {
                count2++
              }
            })
            if (count2 <= 0) {
              count++
            }
          }
        }
      })
      return count > 0
    },

    handleProductsData () {
      const isDefSort = this.data.sort === 'def' // 是否系统排序
      let list = JSON.parse(JSON.stringify(this.selectedProductList))
      let newArr = []
      list.forEach((e, index) => {
        let info = {
          'marketId': e.marketId || '',
          'price': e.price || 0,
          'productId': e.productId || '',
          'productSkuId': e.productSkuId || '0', // 单规格 productSkuId 设为 0
          'sort': isDefSort ? 0 : (e.sort || 0),
          'usePointLimit': e.usePointLimit || 0
        }
        if (e.productStyle === 1) {
          newArr.push(info)
        } else {
          const children = e.stocks || []
          children.forEach(item => {
            if (item.selected) {
              // 默认0 活动 支付方式 0 积分+金额 1 积分 2 金额
              const price = this.payWay === '1' ? '0' : (item.price || 0)
              const usePointLimit = this.payWay === '2' ? '0' : (item.usePointLimit || 0)
              const infos = {
                'marketId': item.marketId || '',
                'price': price,
                'productId': item.productId || '',
                'productSkuId': item.id || '',
                'sort': isDefSort ? 0 : (e.sort || 0),
                'usePointLimit': usePointLimit
              }
              newArr.push(infos)
            }
          })
        }
      })
      this.data.products = newArr
    },

    handleSelectProduct (val) {
      this.data.productData = val || []
      this.handleProductsData()
    }
  },
  destroyed () {
    this.$store.dispatch('clearSelectProduct')
  }
}

</script>
<style lang='scss' scoped>
.row-info {
  margin-left: 30px;
  .title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 30px;
  }
}
</style>
